package com.css.fxfzypg.modules.model.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.similitudeAnalyse.utils.BeanUtil;
import com.css.fxfzypg.modules.model.entity.ResettlementPersonnel;
import com.css.fxfzypg.modules.model.repository.ResettlementPersonnelRepository;
import com.css.fxfzypg.modules.model.service.ResettlementPersonnelService;
import com.css.fxfzypg.modules.model.vo.ResettlementPersonnelVO;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.UUIDGenerator;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author Dbj
 * @date 2022年10月05日  16:11
 */
@Service
public class ResettlementPersonnelServiceImpl implements ResettlementPersonnelService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private SysRoleService roleService;

    @Resource
    ResettlementPersonnelRepository resettlementPersonnelRepository;

    @Resource
    SUserService sUserService;

    @Resource
    private SysAreaService areaService;

    @Override
    public Map<String, Object> getPage(ResettlementPersonnelVO vo, int curPage, int pageSize) {
        Map<String,String> areaMap =(Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"areaMap"));
        Map<String,String> orgMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"orgMap"));
        String userId = PlatformSessionContext.getUserID();
        vo.setUserId(userId);
        //根据用户id查询角色信息 用于数据的查询范围
        String roleByUserId = roleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(roleByUserId, Map.class);
        for(Map roleMap:roleMaps){
            String roleCode =  (String)roleMap.get("roleCode");
            if(roleCode.equals(FxfzConstants.YPG_COUN_YW_ROLE) || roleCode.equals(FxfzConstants.YPG_COUN_GL_ROLE)){
                vo.setNation(true);
            }
        }
        if(vo.getNation()==null){
            vo.setNation(false);
        }
        Map<String, Object> page = resettlementPersonnelRepository.findPage(vo, curPage, pageSize);
        List<ResettlementPersonnel> list = (List<ResettlementPersonnel>) page.get("rows");
        List<ResettlementPersonnel> vos = new ArrayList<>(list.size());
        for(ResettlementPersonnel personnel:list){
            ResettlementPersonnel resettlementPersonnel = new ResettlementPersonnel();
            BeanUtil.copy(personnel,resettlementPersonnel);
            vo.setProvince(areaMap.get(personnel.getProvince()));
            if(!"全部".equals(personnel.getCity())){
                StringBuilder buffer = new StringBuilder();
                List<String> cityList = Arrays.asList(personnel.getCity().split(","));
                for (String s : cityList) {
                    buffer.append(areaMap.get(s)).append(",");
                }
                String cityName = buffer.toString();
                resettlementPersonnel.setCity(cityName.substring(0,cityName.length()-1));
            }
            resettlementPersonnel.setProvince(areaMap.get(personnel.getProvince()));
            vos.add(resettlementPersonnel);
            //casualty.setIsDefault("1".equals(casualty.getIsDefault())?"是":"否");
        }
        page.put("rows",vos);
        return page;
    }

    @Override
    public ResettlementPersonnel getModelById(String id) {
        Map<String,String> areaMap =(Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"areaMap"));
        Map<String,String> orgMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"orgMap"));
        ResettlementPersonnel resettlementPersonnel = resettlementPersonnelRepository.getModelById(id);
        resettlementPersonnel.setProvince(areaMap.get(resettlementPersonnel.getProvince()));
        if(!"全部".equals(resettlementPersonnel.getCity())){
            StringBuffer buffer = new StringBuffer();
            List<String> cityList = Arrays.asList(resettlementPersonnel.getCity().split(","));
            for (String s : cityList) {
                buffer.append(areaMap.get(s)).append(",");
            }
            String cityName = buffer.toString();
            resettlementPersonnel.setCity(cityName.substring(0,cityName.length()-1));
        }
//        CasualtyVO vo = new CasualtyVO();
//        BeanUtil.copy(casualty,vo);
        return resettlementPersonnel;
    }

    @Override
    public ResettlementPersonnel getDefaultModel() {
        return resettlementPersonnelRepository.getDefaultModel();
    }

    @Override
    public List<ResettlementPersonnel> getByDivision(String province, String city, int isNa) {
        return resettlementPersonnelRepository.getByDivision(province,city,isNa);
    }

    @Override
    public ResettlementPersonnel getModelByIdForCopy(String id) {
        Map<String,String> orgMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"orgMap"));
        ResettlementPersonnel personnel = resettlementPersonnelRepository.getModelById(id);
        personnel.setModelName("");
        personnel.setIsDefault("0");
        personnel.setCity("");
        personnel.setProvince("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        personnel.setCreateUserId(userId);
        personnel.setCreateUserName(sUser.getUserName());
        personnel.setOrgId(sUser.getOrgId());
        personnel.setOrgName(orgMap.get(sUser.getOrgId()));
        personnel.setIsValid(YNEnum.Y.toString());
        return personnel;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(ResettlementPersonnel resettlementPersonnel) {
        Map<String,String> orgMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"orgMap"));
        String userId = PlatformSessionContext.getUserID();
        resettlementPersonnel.setId(UUIDGenerator.getUUID());
        resettlementPersonnel.setCreateUserId(userId);
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        resettlementPersonnel.setCreateUserName(sUser.getUserName());
        resettlementPersonnel.setCreateTime(new Date());
        resettlementPersonnel.setOrgId(sUser.getOrgId());
        String orgName = orgMap.get(sUser.getOrgId());
        resettlementPersonnel.setOrgName(orgName);
        resettlementPersonnel.setIsValid(YNEnum.Y.toString());
        String areaCode = areaService.getDivisionCodeById(resettlementPersonnel.getProvince());
        areaCode =(String) JSONObject.parse(areaCode);
        resettlementPersonnel.setProvinceCode(areaCode);
        resettlementPersonnelRepository.save(resettlementPersonnel);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ResettlementPersonnel resettlementPersonnel) {
        ResettlementPersonnel personnel = resettlementPersonnelRepository.getModelById(resettlementPersonnel.getId());
        String userId = PlatformSessionContext.getUserID();
        if(!userId.equals(personnel.getCreateUserId())){
            throw new RuntimeException("修改失败，只能修改自己创建的模型");
        }
        BeanUtil.copy(resettlementPersonnel,personnel);
        resettlementPersonnel.setUpdateUserId(userId);
        resettlementPersonnel.setUpdateTime(new Date());
        resettlementPersonnelRepository.update(resettlementPersonnel);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        ResettlementPersonnel personnel = resettlementPersonnelRepository.getModelById(id);
        String userId = PlatformSessionContext.getUserID();
        if(!userId.equals(personnel.getCreateUserId())){
            throw new RuntimeException("删除失败，只能删除自己创建的模型");
        }
        resettlementPersonnelRepository.delete(userId,new Date(),id);
    }

    @Override
    public ResettlementPersonnel getModel1ById(String id) {
        ResettlementPersonnel resettlementPersonnel = resettlementPersonnelRepository.getModelById(id);
        return resettlementPersonnel;
    }
}
